/**
 * Created by Administrator on 2017/3/3.
 */
var express = require('express');

var moment = require('moment');

var router = express.Router();

var module_collection = require('../module/database');

var Comment = module_collection.Comment;

var Theme = module_collection.Theme;

var Subscribe = module_collection.Subscribe;

var History = module_collection.History;

var MyTheme = module_collection.MyTheme

var MyComment = module_collection.MyComment;

var Forum = module_collection.Forum;

var User = module_collection.User;


// 主题刘表
router.get('/themeList', function (req, res) {
    var user_id = req.cookies.wcID;
    var forum_id = req.query.forum_id;
    var page = req.query.page;
    // console.log(page);
    if(forum_id == undefined){
        forum_id = 1;
    }
    if (page == undefined) {
        page = 1;
    }
    Theme.find({forum_id:forum_id,permission:1},function (err, data) {
        if (err) {
            console.log('主题列表查询失败')
        } else {         
            var maindata = data;
            if (data != null) {
                console.log('主题查询成功');
                Forum.find(function(err,data){
                    var leftNav = data;
                    Subscribe.count({update:true,user_id:user_id},function (err,data) {
                        var subCount = data;
                        console.log(subCount);
                        MyComment.count({update:true,user_id:user_id},function (err,data) {
                           var myComCount = data; 
                            Theme.count(function (err,count) {
                                res.status(200).json({
                                    title: "主题",
                                    main: maindata,
                                    leftNav:leftNav,
                                    newReply:myComCount,
                                    newSub:subCount, 
                                    total: Math.ceil(count / 10),                       
                                })  
                            })           
                        });
                    })               
                }) 
                
            } else {

            }
        }
    }).sort({
        update_time: -1
    }).skip((page - 1) * 10).limit(10).populate('user_info');
   
});


router.get('/newData', function (req, res) {
    var page = req.query.page;
    if (page == undefined) {
        page = 1;
    }

    Theme.find(function (err, data) {
        if (err) {
            console.log('主题列表查询失败')
        } else {
            if (data != null) {
                console.log('留言查询成功');
                Theme.count(function (err, count) {
                    if (!err) {
                        res.status(200).json({
                            data: data,
                            total: Math.ceil(count / 10)
                        });
                    }
                });
            } else {

            }
        }
    }).sort({
        update_time: -1
    }).skip((page - 1) * 10).limit(20)

});

//发表主题
router.get('/posting', function (req, res) {
    res.render('reply', {
        title: "发表主题"
    });
});

//留言列表
router.get('/theme', function (req, res) {
    var comment_id = req.query.com_id;
    console.log(req.query);
    var theme_id = req.query.id;
    var user_id = req.cookies.wcID;
    var page = req.query.page;
    var subed;
    if (user_id) {
        console.log('已登陆');
    }
    if (page == undefined) {
        page = 1;
    }
    Comment.find({
        theme_id: theme_id
    }, function (err, data) {
        if (err) {
            console.log('留言列表查询失败');
        } else {
            if (data != null) {           
                    Subscribe.update({
                        theme_id: theme_id,
                        user_id: user_id
                    }, {
                        update: false
                    }, function (err,count) {
                        // console.log(data);
                    });
                    if(comment_id != 'false'){
                        console.log(user_id)
                        console.log(comment_id);
                        MyComment.update({
                            user_id:user_id,
                            comment_id:comment_id
                        },{
                            update:false
                        },function(err,count){
                            console.log(count);
                        })
                    }
                    
                var com_data = data;
                Theme.find({
                    id: theme_id,
                    permission:1
                }, function (err, data) {
                    if (!err) {
                        var theme_data = data[0];
                        Subscribe.find({user_id:user_id,theme_id:theme_id},function(err,data){
                            if(data.length == 0){
                                subed = false;
                            }else{
                                subed = true;
                            }
                            Comment.count({theme_id:theme_id},function(err,count){
                                res.status(200).json({
                                    title: "留言列表",
                                    theme_id: theme_id,
                                    reply: com_data,
                                    theme:theme_data,
                                    authorId: user_id,
                                    subed:subed,       
                                    total: Math.ceil(count / 10)  
                                });
                            })
                        })
                        
                    }
                }).populate('user_info');
                console.log('留言查询成功');
            } else {
            }
        }
    }).skip((page - 1) * 10).limit(10);
});

//发表留言
router.get('/reply', function (req, res) {
    var com_id = '';
    if (req.query.com_id != null) {
        com_id = req.query.com_id;
    }
    console.log(com_id);
    res.render('reply', {
        title: "发表留言",
        theme_id: req.query.id,
        com_id: com_id
    });
});

//个人信息表 
router.get('/userinfo', function (req, res) {
    var user_id = req.cookies.wcID;
    MyTheme.count({
        user_id: user_id
    }, function (err, count) {
        if (!err) {
            console.log(count + 'themeCount');
            MyComment.count({
                user_id: user_id
            }, function (err, count) {
                if (!err) {
                    console.log(count + 'commentCount');
                    History.count({
                        user_id: user_id
                    }, function (err, count) {
                        if (!err) {
                            console.log(count + 'history')
                            Subscribe.count({
                                user_id: user_id
                            }, function (err, count) {
                                console.log(count + 'subscribe');
                            })
                        }
                    })
                }
            })
        }
    })
})

//订阅
router.get('/subscribe', function (req, res) {
    var id = req.cookies.wcID;
    Subscribe.find({
        user_id: id
    }, function (err, data) {
        if (!err) {
            Subscribe.count({user_id:id},function(err,count){
                res.status(200).json({
                    title: "订阅",
                    data: data,
                    total: Math.ceil(count / 10)
                });
            })
            
        }
    }).sort({update:-1}).populate('theme_info')
});

//搜索
router.get('/search', function (req, res) {
    res.render('search', {});
})

//我的留言
router.get('/mycomment', function (req, res) {
    var user_id = req.cookies.wcID;
    MyComment.find({
        user_id: user_id
    }, function (err, data) {
        if (!err) {
            res.status(200).json({
                data: data,
                title: '我的留言'
            })
            // console.log(data);
        }
    }).sort({
        update: -1
    }).populate('comment_info');
})

//我的主题
router.get('/mytheme', function (req, res) {
    var user_id = req.cookies.wcID;
    MyTheme.find({
        user_id: user_id
    }, function (err, data) {
        if (!err) {
            res.status(200).json({
                data: data,
                title: '我的主题'
            })
            // console.log(data);
        }
    }).sort({
        theme_id: -1
    }).populate('theme_info').populate('user_info');
})

router.get('/register', function (req, res) {
    res.render('register', {});
})

router.get('/register2', function (req, res) {
    res.render('register2', {});
});

router.get('/forum',function(req,res){
    Forum.find(function(err,data){
        if(!err){
            res.status(200).json({sectionTitle:data});
        }
    })
})



router.get('/manage/login',function(req,res){
	res.render('login');
});


//假设规定一页显示 8 条
var countOfPage = 8;
//获取用户首页页面
router.get('/manage/',function(req,res){
	//page:表示要展示第几页数据，假设获取第一页 
	var page = Number(req.query.page);
	if (!page) {
		page = 1;
	}
	//先获取所有学生个数
	User.count(function(err,total){
		var allPages =Math.ceil(total / countOfPage);
		//console.log(page);
		//console.log(total);
		//判断用户传递过来的 page 是否是脏数据(小于1或者大于总页数)
		if (page > allPages) {
			page = allPages;
		}
		if (page < 1) {
			page = 1;
		}
		//console.log(page);
		//console.log(allPages);
		//获取前几页和后几页
		var showPages = getShowPages(page,allPages);
		
		//查询数据
		User.find(function(err,data){
			if (!err) {
				var title = '吐槽信息查询管理';
				res.render('index',{title,data,allPages,page,showPages})
			} else{
				res.status(200).send('查询失败');
			}
		}).skip((page - 1) * countOfPage).limit(countOfPage);
	});
	
});

//获取吐槽信息页面
router.get('/manage/theme',function(req,res){
	//page:表示要展示第几页数据，假设获取第一页 
	var page = Number(req.query.page);
	if (!page) {
		page = 1;
	}
	//先获取所有学生个数
	Theme.count(function(err,total){
		var allPages =Math.ceil(total / countOfPage);
		//console.log(page);
		//console.log(total);
		//判断用户传递过来的 page 是否是脏数据(小于1或者大于总页数)
		if (page > allPages) {
			page = allPages;
		}
		if (page < 1) {
			page = 1;
		}
		//console.log(page);
		//console.log(allPages);
		//获取前几页和后几页
		var showPages = getShowPages(page,allPages);
		
		//查询数据
		Theme.find(function(err,data){
			if (!err) {
				var title = '吐槽信息查询管理';
                console.log(data);
				res.render('theme',{title,data,allPages,page,showPages})
			} else{
				res.status(200).send('查询失败');
			}
		}).skip((page - 1) * countOfPage).limit(countOfPage).populate('user_info');
	});
});
router.get('/manage/answer',function(req,res){
	//page:表示要展示第几页数据，假设获取第一页 
	var page = Number(req.query.page);
	if (!page) {
		page = 1;
	}
	//先获取所有学生个数
	Comment.count(function(err,total){
		var allPages =Math.ceil(total / countOfPage);
		//console.log(page);
		//console.log(total);
		//判断用户传递过来的 page 是否是脏数据(小于1或者大于总页数)
		if (page > allPages) {
			page = allPages;
		}
		if (page < 1) {
			page = 1;
		}
		//console.log(page);
		//console.log(allPages);
		//获取前几页和后几页
		var showPages = getShowPages(page,allPages);
		
		//查询数据
		Comment.find(function(err,data){
			if (!err) {
				var title = '吐槽信息查询管理';
				res.render('answer',{title,data,allPages,page,showPages})
			} else{
				res.status(200).send('查询失败');
			}
		}).skip((page - 1) * countOfPage).limit(countOfPage);
	});
	
});

//根据当前页和总的页数，获取前几页和后几页
function getShowPages(page,allPages){
	//showPages 保存当前点击的这一页的前几页和后几页
	var showPages = [];
	if (allPages < 5) {
		for (var i = 0; i < allPages; i++) {
			showPages[i] = i + 1;
		}
	} else{
		//方案：够用的情况下，当前页位置停留在中间
		showPages.push(page);
		var offset = 1;
		while(showPages.length < 5){
			if (page - offset > 0) {
				showPages.unshift(page - offset);
			}
			if (page + offset <= allPages) {
				showPages.push(page + offset);
			}
			offset ++;
		}
		
	}
	return showPages;
}

module.exports = router;